import type { ComponentStyleIdType } from '../types/interfaces'
import { StyleManager } from '../module/style_manager'
import { ComponentStyleId, logger } from '../types/constants'
import { FeatureToggle } from '../user_center/feature_toggle'
import { About } from '../user_center/tab/about'
import { Announcement } from '../user_center/tab/announcement'
import { Feedback } from '../user_center/tab/feed_back'
import { Personalization } from '../user_center/tab/personalization'
import { UtilitySettings } from '../user_center/tab/utility_settings'
import { UserCenter } from '../user_center/user_center'
import { DonateManager } from './donate'

export class Menu {
  readonly styleId: string = ComponentStyleId[this.name]
  public featureToggle: FeatureToggle | undefined
  private donateToast: DonateManager | undefined
  private feedback: Feedback | undefined
  private announcementBanner: Announcement | undefined
  private utilitySettings: UtilitySettings | undefined
  private personalization: Personalization | undefined
  private about: About | undefined
  private userCenter: UserCenter | undefined

  get name(): ComponentStyleIdType {
    return 'Menu'
  }

  /**
   * 初始化菜单
   */
  public async init(): Promise<void> {
    // 用户中心先初始化，因为用户中心本身就会先将模块进行初始化一次，然后这些模块使用 getInstance 获取之前的实例即可（非常重要！！！）
    this.userCenter = await UserCenter.create()

    this.announcementBanner = Announcement.getInstance()
    this.featureToggle = FeatureToggle.getInstance()
    this.utilitySettings = UtilitySettings.getInstance()
    this.personalization = Personalization.getInstance()
    this.feedback = Feedback.getInstance()
    this.about = About.getInstance()
    this.donateToast = DonateManager.getInstance()

    this.personalization.init().catch((err) => {
      logger.error(`[${this.name}] 个性化化初始化失败`, err)
    })

    await this.register()

    StyleManager.getInstance().registerStyle(this.styleId, this.getStyles(), false, true)
  }

  /**
   * 注册菜单命令
   */
  public async register(): Promise<void> {
    GM_registerMenuCommand('👨‍💻 用户中心', async () => {
      this.userCenter?.showDialog()
    })

    GM_registerMenuCommand('💖 赞助开发', async () => {
      await this.donateToast?.showDialog()
    })

    this.userCenter?.showDialog(true)
  }

  getStyles(): string {
    return `
      ${this.announcementBanner?.styles()}
      ${this.featureToggle?.styles()}
      ${this.utilitySettings?.styles()}
      ${this.personalization?.styles()}
      ${this.about?.styles()}
      ${this.feedback?.styles()}
      ${this.userCenter?.styles()}
      ${this.donateToast?.styles()}
    `
  }
}
